package com.common.orm;

import com.common.orm.sqlparameters.SQLParameterException;
import com.common.orm.sqlparameters.SqlParameter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author dsavchenko
 */
class SqlExecuter {

    protected PreparedStatement preparedStatement;
    protected Map<String, SqlParameter> values = new TreeMap<String, SqlParameter>();
    
    protected void init(Connection connection,String sql,ClassData classData,SqlParameter... values) throws SQLException{
        while(true){
            try{
                preparedStatement = connection.prepareStatement(sql);
                processParameters(values);
                break;//if no exceptions throws, we just exit
            }catch(SQLException ex){
                DBIssuesResolver resolver=new DBIssuesResolver();
                resolver.setClassData(classData);
                boolean result=resolver.resolveProblem(connection, ex.getMessage());
                if(result==false){
                    throw ex;
                }
            }
        }
    }
    
    void fillWithParams(int startIndex, ArrayList<Placeholder> placeholders) throws SQLParameterException, SQLException {
        for (Placeholder pl : placeholders) {
            SqlParameter param = values.get(pl.getName());
            if (param == null) {
                throw new SQLParameterException("You have not provided value for parameter [" + pl.getName() + "]");
            }
            param.process(pl.getPosition() + startIndex, preparedStatement);
        }
    }

    protected void processParameters(SqlParameter... values) {
        for (SqlParameter param : values) {
            this.values.put(param.getName(), param);
        }
    }
}
